import scrapy

from scrapy_dytt8_35.items import ScrapyDytt835Item


class MvSpider(scrapy.Spider):
    name = "mv"
    allowed_domains = ["www.dytt8.net"]
    start_urls = ["https://www.dytt8.net/index2.htm"]

    def parse(self, response):
        # 先获取到name和链接地址，再通过链接跳转第二页，拿到图片的src

        name_list = response.xpath('//div[@class="co_area2"]//tr//a[2]')
        # 有相同的xpath地址，就一起for循环,前面加.号，不然调用不了
        for i in name_list:
            name = i.xpath('./text()').extract_first()
            href = i.xpath('./@href').extract_first()
            # print(name,href)
            url = 'https://www.dytt8.net' + href
            # 获取到链接地址，发起请求，跳转第二页，meta是个字典，传递参数，将name传到parse_second方法中
            yield scrapy.Request(url,callback=self.parse_second,meta={'name':name})

    def parse_second(self,response):
        # 此处获取不到img,问题在xpath中，//div[@id="Zoom"]//span/img/@src，里面有span就获取不到，去掉span就可以
        src = response.xpath('//div[@id="Zoom"]//img/@src').extract_first()
        # print(src)
        name = response.meta['name']
        # print(name)

        # 调用items中的方法
        movie = ScrapyDytt835Item(name=name,src=src)

        # yield将数据传给pipelines,再回到这个步骤的下一行继续执行
        yield movie

